﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfileContributeInfo")]
	public class ProfileContributeInfoController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ProfileContributeInfoModel model)
		{

			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from conferenceContributeInfo in DbContext.ConferenceContributeInfo.AsNoTracking()
					.Where(x => x.Creator == LoginUser.UserName)
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
				      on conferenceContributeInfo.ConferenceId equals conferenceMaster.ID
				  select new
				  {
					  id = conferenceContributeInfo.ID,
					  conferenceName = conferenceMaster.ConferenceName,
					  conferenceId = conferenceMaster.ID,
					  createDate = conferenceContributeInfo.CreateDate,
					  contributationStatus = conferenceContributeInfo.ContributationStatus,
					  essayTitle = conferenceContributeInfo.EssayTitle,
					  sort = conferenceContributeInfo.Sort,
					  HomePageUrl = conferenceMaster.HomePageUrl,
					  ConferenceNickName = conferenceMaster.ConferenceNickName,
					  IsInternational = conferenceMaster.IsInternational,
					  CreateDate = conferenceContributeInfo.CreateDate,
					  adminStatus = conferenceContributeInfo.AdminStatus
				  };

			if (!string.IsNullOrWhiteSpace(model.queryConferenceName) && model.queryConferenceName != "")
			{
				sql = sql.Where(x => x.conferenceName.Contains(model.queryConferenceName));
			}
			if (!string.IsNullOrWhiteSpace(model.queryEssayTitle) && model.queryEssayTitle != "")
			{
				sql = sql.Where(x => x.essayTitle.Contains(model.queryEssayTitle));
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderByDescending(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				id = x.id,
				conferenceId = x.conferenceId,
				conferenceName = x.conferenceName,
				contributationStatus = x.contributationStatus,
				essayTitle = x.essayTitle,
				createDate = !x.IsInternational ? x.createDate.Value.ToString("yyyy-MM-dd") : x.createDate.Value.ToString("MM/dd/yyyy"),
				homePageUrl = x.HomePageUrl,
				conferenceNickName = x.ConferenceNickName,
				IsInternational = x.IsInternational 
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		public async Task<JsonResult> Modify(ConferenceContributeInfoModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			if (model.AbstractFile != null || model.SupplementaryFile != null)
			{
				var msg = await this.SaveFiles(model);
				if (!string.IsNullOrEmpty(msg))
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(msg),
							JsonRequestBehavior.AllowGet);
				}
			}

			var result = await DbContext.ConferenceContributeInfo
					.FirstOrDefaultAsync(x => x.ID == model.ContributeId);

			if (result != null)
			{
				if (result.EssayTitle != model.EssayTitle)
				{
					result.EssayTitle = model.EssayTitle;
				}
				if (result.Keyword != model.Keyword)
				{
					result.Keyword = model.Keyword;
				}
				if (result.ProgramAbstract != model.ProgramAbstract)
				{
					result.ProgramAbstract = model.ProgramAbstract;
				}
				if (result.Abstract != model.Abstract)
				{
					result.Abstract = model.Abstract;
				}
				if (!string.IsNullOrWhiteSpace(model.AbstractFilePath))
				{
					if (model.AbstractFilePath == ConstValues.clearFlg)
					{
						result.AbstractFile = string.Empty;
					}
					else
					{
						result.AbstractFile = model.AbstractFilePath;
					}
				}
				if (!string.IsNullOrWhiteSpace(model.SupplementaryFilePath))
				{
					if (model.SupplementaryFilePath == ConstValues.clearFlg)
					{
						result.SupplementaryFile = string.Empty;
					}
					else
					{
						result.SupplementaryFile = model.SupplementaryFilePath;
					}
				}
				if (result.TopicId != model.Topic)
				{
					result.TopicId = model.Topic;
				}
				if (result.EssayId != model.Essay)
				{
					result.EssayId = model.Essay;
				}
				if (result.ReportId != model.Report)
				{
					result.ReportId = model.Report;
				}
				if (result.OcisId != model.Ocis)
				{
					result.OcisId = model.Ocis;
				}
				if (result.JournalId != model.Journal)
				{
					result.JournalId = model.Journal;
				}

				result.Updater = LoginUser.UserName;
				result.UpdateIP = LoginUser.IP;
				result.UpdateDate = DateTime.Now;

				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[Route("Delete/{id}")]
		public async Task<JsonResult> Delete(string id)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var exist = await DbContext.ReviewInfo.AsNoTracking()
					.Where(x => x.ContributeId == id)
					.ToListAsync();

			if (exist.Count > 0)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgReviewHasStart),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.ConferenceContributeInfo
					.FirstOrDefaultAsync(x => x.ID == id);

			if (result != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					DbContext.ConferenceContributeInfo.Remove(result);

					var authorInfoList = await DbContext.AuthorInfo
							.Where(x => x.ContributeId == id).ToListAsync();
					DbContext.AuthorInfo.RemoveRange(authorInfoList);

					var affiliationInfoList = await DbContext.AffiliationInfo
							.Where(x => x.ContributeId == id).ToListAsync();
					DbContext.AffiliationInfo.RemoveRange(affiliationInfoList);

					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> ChangeContactAuthor(ConferenceContributeInfoModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.AuthorInfo
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				if (result.IsContactAuthor)
				{
					result.IsContactAuthor = false;
				}
				else
				{
					result.IsContactAuthor = true;
				}

				result.Updater = LoginUser.UserName;
				result.UpdateIP = LoginUser.IP;
				result.UpdateDate = DateTime.Now;

				await DbContext.SaveChangesAsync();

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> ChangePresenter(ConferenceContributeInfoModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.AuthorInfo
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					var authorInfo = DbContext.AuthorInfo.Where(x => x.ContributeId == result.ContributeId).ToList();
					foreach (var author in authorInfo)
					{
						if (author.ID == model.Id)
						{
							author.IsPresenter = true;
							author.Updater = LoginUser.UserName;
							author.UpdateIP = LoginUser.IP;
							author.UpdateDate = DateTime.Now;
						}
						else
						{
							author.IsPresenter = false;
							author.Updater = LoginUser.UserName;
							author.UpdateIP = LoginUser.IP;
							author.UpdateDate = DateTime.Now;
						}
					}
					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}
				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> CreateAuthor(AuthorModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var tmpName = !string.IsNullOrEmpty(model.FullName) ? model.FullName?.Trim() :
						Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(),
							Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En ?
							ConstValues.Language.En : ConstValues.Language.Cn);

			var result = await DbContext.AuthorInfo
					.FirstOrDefaultAsync(x => x.ConferenceId == model.ConferenceId &&
						x.ContributeId == model.ContributeId &&
						x.Mail == model.Mail);

			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgTheSameMail),
							JsonRequestBehavior.AllowGet);
			}

			using (var transaction = DbContext.Database.BeginTransaction())
			{
				var authorInfo = new AuthorInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AuthorInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					FamilyName = model.FamilyName?.Trim(),
					FirstName = model.FirstName?.Trim(),
					FullName = tmpName,
					Department = model.Department?.Trim(),
					Country = model.Country,
					State = model.State,
					City = model.City,
					Address = model.Address?.Trim(),
					ZipCode = model.ZipCode?.Trim(),
					Mobile = model.Mobile?.Trim(),
					Mail = model.Mail?.Trim(),
					CcMail = model.CcMail?.Trim(),
					SelfIntroduction = model.SelfIntroduction?.Trim(),
					Status = model.Status,
					Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = DateTime.Now
				};
				DbContext.AuthorInfo.Add(authorInfo);

				await this.UpdateAffiliation(model);

				await DbContext.SaveChangesAsync();
				transaction.Commit();
			}

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> EditAuthor(AuthorModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var tmpName = !string.IsNullOrEmpty(model.FullName) ? model.FullName?.Trim() :
						Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(),
							Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En ?
							ConstValues.Language.En : ConstValues.Language.Cn);

			var exist = await DbContext.AuthorInfo
					.FirstOrDefaultAsync(x => x.ID != model.Id &&
						x.ConferenceId == model.ConferenceId &&
						x.ContributeId == model.ContributeId &&
						x.Mail == model.Mail);

			if (exist != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgTheSameMail),
							JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.AuthorInfo.FirstOrDefaultAsync(x => x.ID == model.Id);			

			if (result != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					result.FamilyName = model.FamilyName?.Trim();
					result.FirstName = model.FirstName?.Trim();
					result.FullName = tmpName;
					result.Department = model.Department?.Trim();
					result.Country = model.Country;
					result.State = model.State;
					result.City = model.City;
					result.Address = model.Address?.Trim();
					result.ZipCode = model.ZipCode?.Trim();
					result.Mobile = model.Mobile?.Trim();
					result.Mail = model.Mail?.Trim();
					result.CcMail = model.CcMail?.Trim();
					result.IsFirstAuthor = false;
					result.IsContactAuthor = false;
					result.IsPresenter = false;
					result.SelfIntroduction = model.SelfIntroduction?.Trim();
					result.Status = model.Status;
					result.Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort;
					result.Remark = model.Remark?.Trim();
					result.Updater = LoginUser.UserName;
					result.UpdateIP = LoginUser.IP;
					result.UpdateDate = DateTime.Now;

					model.OriginalMail = DbContext.AuthorInfo.AsNoTracking().FirstOrDefault(x => x.ID == model.Id).Mail;
					await this.UpdateAffiliation(model);

					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}

				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> DeleteAuthor(AuthorModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var authorCount = await DbContext.AuthorInfo.AsNoTracking()
					.CountAsync(x => x.ID != model.Id && x.ContributeId == model.ContributeId);

			if (authorCount == 0)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(string.Format(Resources.MsgIsEmpty, Resources.Author)),
						JsonRequestBehavior.AllowGet);
			}

			var result = await DbContext.AuthorInfo
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result != null)
			{
				if (result.IsPresenter)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgIsPresenter),
						JsonRequestBehavior.AllowGet);
				}
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					var contributeId = result.ContributeId;
					var conferenceId = result.ConferenceId;
					var id = result.ID;
					var mail = result.Mail;
					DbContext.AuthorInfo.Remove(result);
					var currentAuthor = DbContext.AuthorInfo.Where(x => x.ContributeId == contributeId && x.ConferenceId == conferenceId && x.ID != id).OrderBy(x => x.Sort).ThenBy(x => x.CreateDate).ToList();
					for(var i = 0;i< currentAuthor.Count; i++)
					{
						currentAuthor[i].Sort = i + 1;
					}
					var affiliationInfo = await DbContext.AffiliationInfo.Where(x => x.ConferenceId == conferenceId && x.ContributeId == contributeId && x.Mail == mail).ToListAsync();
					DbContext.AffiliationInfo.RemoveRange(affiliationInfo);
					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}
				return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessDelete),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> ApplyOrDecline(ConferenceContributeInfoModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.ProfileAwardsInfo
					.FirstOrDefaultAsync(x => x.AwardsId == model.Id &&
						x.ContributeId == model.ContributeId &&
						x.UserName == LoginUser.UserName);

			if (result != null)
			{
				DbContext.ProfileAwardsInfo.Remove(result);
			}
			else
			{
				var profileAwardsInfo = new ProfileAwardsInfo() {
					ID = Utility.GetTableId(ConstValues.TableName.ProfileAwardsInfo),
					UserName = LoginUser.UserName,
					ContributeId = model.ContributeId,
					AwardsId = model.Id,
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = DateTime.Now
				};

				DbContext.ProfileAwardsInfo.Add(profileAwardsInfo);
			}

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		private async Task<string> SaveFiles(ConferenceContributeInfoModel model)
		{
			string nickName = DbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId)?.ConferenceNickName;
			string folder = Path.Combine(ConstValues.Uploads, nickName);
			string pfolder = Path.Combine(Server.MapPath(ConstValues.Uploads), nickName);

			var journalId = string.Empty;
			if (!string.IsNullOrEmpty(model.Journal))
			{
				var journalMaster = await DbContext.JournalMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == model.Journal &&
							x.ConferenceId == model.ConferenceId);
				journalId = journalMaster.JournalId;
				folder = Path.Combine(folder, journalMaster.JournalId);
			}

			if (!string.IsNullOrEmpty(journalId))
			{
				pfolder = Path.Combine(pfolder, journalId);
			}

			if (model.AbstractFile != null)
			{
				if (model.AbstractFile.ContentLength > ConstValues.FileMaxLength)
				{
					return Resources.MsgFileOverflowError;
				}

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.AbstractFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.AbstractFile.FileName);
				model.AbstractFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.AbstractFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}

			if (model.SupplementaryFile != null)
			{
				if (model.SupplementaryFile.ContentLength > ConstValues.FileMaxLength)
				{
					return Resources.MsgFileOverflowError;
				}

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.SupplementaryFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.SupplementaryFile.FileName);
				model.SupplementaryFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.SupplementaryFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}
			return string.Empty;
		}

		private async Task UpdateAffiliation(AuthorModel model)
		{
			var mail = !string.IsNullOrEmpty(model.OriginalMail) ? model.OriginalMail : model.Mail;
			var affiliationList = await DbContext.AffiliationInfo
					.Where(x => x.ConferenceId == model.ConferenceId &&
						x.ContributeId == model.ContributeId &&
						x.Mail == mail)
					.ToListAsync();

			DbContext.AffiliationInfo.RemoveRange(affiliationList);

			var dt = DateTime.Now;

			#region 单位0
			if (!string.IsNullOrEmpty(model.Affiliation0))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation0?.Trim(),
					Country = model.Country0,
					Status = model.Status,
					Sort = 0,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位1
			if (!string.IsNullOrEmpty(model.Affiliation1))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation1?.Trim(),
					Status = model.Status,
					Country = model.Country1,
					Sort = 1,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位2
			if (!string.IsNullOrEmpty(model.Affiliation2))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation2?.Trim(),
					Status = model.Status,
					Country = model.Country2,
					Sort = 2,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位3
			if (!string.IsNullOrEmpty(model.Affiliation3))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation3?.Trim(),
					Country = model.Country3,
					Status = model.Status,
					Sort = 3,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位4
			if (!string.IsNullOrEmpty(model.Affiliation4))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation4?.Trim(),
					Country = model.Country4,
					Status = model.Status,
					Sort = 4,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位5
			if (!string.IsNullOrEmpty(model.Affiliation5))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation5?.Trim(),
					Country = model.Country5,
					Status = model.Status,
					Sort = 5,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位6
			if (!string.IsNullOrEmpty(model.Affiliation6))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation6?.Trim(),
					Country = model.Country6,
					Status = model.Status,
					Sort = 6,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位7
			if (!string.IsNullOrEmpty(model.Affiliation7))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation7?.Trim(),
					Country = model.Country7,
					Status = model.Status,
					Sort = 7,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位8
			if (!string.IsNullOrEmpty(model.Affiliation8))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation8?.Trim(),
					Country = model.Country8,
					Status = model.Status,
					Sort = 8,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位9
			if (!string.IsNullOrEmpty(model.Affiliation9))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation9?.Trim(),
					Country = model.Country9,
					Status = model.Status,
					Sort = 9,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
		}
	}
}